package com.kly.sc.api.application.controller.adjust;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.StringUtils;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.kly.sc.api.application.annos.InitUser;
import com.kly.sc.api.application.annos.SignIgnore;
import com.kly.sc.api.application.annos.VisitorAccessible;
import com.kly.sc.api.application.controller.adjust.request.AdjustInfoReq;
import com.kly.sc.api.application.helper.RequestLocalInfo;
import com.kly.sc.api.application.interceptors.RequestWrapper;
import com.kly.sc.api.application.service.utils.BaseComponent;
import com.kly.user.dto.AdJustUserMappingReq;
import com.kly.user.dto.StoreReportReq;
import com.kly.user.service.AdjustService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("api/adjust")
public class AdjustController extends BaseComponent {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    AdjustService adjustService;


    @ResponseBody
    @RequestMapping(value = "/receive/msg", method = RequestMethod.GET)
    @VisitorAccessible
    @SignIgnore
    public void receiveMsg(HttpServletRequest request, HttpServletResponse response) {
        try {
            Enumeration<String> parameterNames = request.getParameterNames();
            Map<String, Object> parametersMap = new HashMap<>();

            // 遍历所有参数
            while (parameterNames.hasMoreElements()) {
                String paramName = parameterNames.nextElement();
                String paramValue = request.getParameter(paramName);
                parametersMap.put(paramName, paramValue);
            }

            final String adjustStr = JSONObject.toJSONString(parametersMap);

            logger.info("====receiveAdjustReportSuccess==== params :{}", adjustStr);
            adjustService.storeAppsFlyerReport(StoreReportReq.builder().reportContent(adjustStr).build());
        } catch (Exception e) {
            logger.info("====receiveAdjustReportFailed====", e);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/receive/install/msg", method = RequestMethod.GET)
    @VisitorAccessible
    @SignIgnore
    public void receiveInstallMsg(HttpServletRequest request, HttpServletResponse response) {
        try {
            RequestWrapper requestWrapper = new RequestWrapper(request);
            StringBuilder requestBody = new StringBuilder();
            BufferedReader bufferedReader = requestWrapper.getReader();
            String line;

            while ((line = bufferedReader.readLine()) != null) {
                requestBody.append(line);
            }
//            final StoreReportReq storeReportReq = StoreReportReq.builder().reportContent(paramStr).build();
//            adjustService.storeAppsFlyerReport(storeReportReq);

            logger.info("====receiveAdjustReportSuccess==== params :{}", requestBody.toString());
            logger.info("====receiveAdjustReportSuccess==== params :{}", JSONUtil.toJsonPrettyStr(request));

        } catch (Exception e) {
            logger.info("====receiveAdjustReportFailed====", e);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/addAdjustInfo")
    @InitUser
    public Response addAdjustInfo(@RequestBody AdjustInfoReq req) {
        String request = JsonStream.serialize(req);
        final String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        logger.info("====addAdjustInfo start====,userCode:{},params:{}", userCode, request);
        String content = null;
        String channel = null;
        String campaign = null;
        String afAdset = null;
        String afAd = null;
        try {
            if (StringUtils.isNotEmpty(req.getChannel())) {
                content = req.getChannel();

                if (StringUtils.isNotEmpty(content) && JSONUtil.isJson(content)) {
                    content = req.getChannel();
                    String ad_channel = JsonIterator.deserialize(content).get("network").toString();
                    try {
                        Any fbInstallReferrer = JsonIterator.deserialize(content).get("fbInstallReferrer");
                        ad_channel = JsonIterator.deserialize(fbInstallReferrer.toString()).get("fb_install_referrer_publisher_platform").toString();
                    } catch (Exception e) {
                        logger.error("==addAdjustInfo 解析渠道有异常 ==", e);
                    }

                    if (StringUtils.isNotEmpty(ad_channel)) {
                        channel = ad_channel;
                    }
                    campaign = JsonIterator.deserialize(content).get("campaign").toString();
                    afAdset = JsonIterator.deserialize(content).get("adgroup").toString();
                    afAd = JsonIterator.deserialize(content).get("creative").toString();
                }
            }
        } catch (Exception e) {
            logger.error("====addAdjustInfo error====,userCode:{},params:{}", userCode, request, e);
        }

        AdJustUserMappingReq adJustUserMappingReq = AdJustUserMappingReq.builder().userCode(userCode)
                .adid(req.getAdid()).channel(channel).content(req.getChannel()).campaign(campaign).afAdset(afAdset).afAd(afAd).build();
        adjustService.queryOrStoreIfNotExists(adJustUserMappingReq);

        return Response.ok();
    }
}
